package com.nd.android.musicboxlibrary.ui.adapter;

import java.util.HashMap;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.common.utils.StarAppUtils;
import com.common.StarAppConfig;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.BusProvider;
import com.nd.android.musicboxlibrary.business.comm.MagicNumber;
import com.nd.android.musicboxlibrary.business.comm.MenuPositionEvent;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.ui.common.UnMixable;
import com.nd.android.musicboxlibrary.util.MusicBoxUtils;
import com.ngds.library.downloadcenter.AppDownloadHelper;
import com.ngds.library.downloadcenter.AppDownloadHelperImpl;
import com.ngds.library.downloadcenter.DownloadBytesAndStatusWrapper;
import com.product.android.utils.LogUtils;

/**
 * 下载列表适配器
 */
public class MyMusicDownLoadAdapter extends AbstractAdapter<MusicInfo, MusicDownLoadViewHolder>
implements AdapterView.OnItemClickListener, MagicNumber {

	/**
	 * 
	 * <br>Created 2014年11月28日 上午12:05:46
	 * @author       wat.ztag
	 */
	@Override
	public void initMagicNumber() {
	}

	private HashMap<Integer, Boolean> state = new HashMap<Integer, Boolean>();
	private AppDownloadHelper mAppDownloadHelper;
	private TextView mTvFooter;

	/**
	 * Creates a new instance of MyMusicDownLoadAdapter. <br>
	 * Created 2014年9月15日 下午11:08:02
	 * 
	 * @param context Context
	 * @param tvFooter TextView
	 */
	public MyMusicDownLoadAdapter(Context context, TextView tvFooter) {
		super(context);
		this.mTvFooter = tvFooter;
		mAppDownloadHelper = AppDownloadHelperImpl.getInstance(context);

	}

	@Override
	protected MusicDownLoadViewHolder getNewHolder() {
		return new MusicDownLoadViewHolder();
	}

	@Override
	protected int getItemLayout() {
		return R.layout.mbx_my_music_download_item;
	}

	@Override
	public void bindView(final MusicDownLoadViewHolder holder, final MusicInfo data,
			final int position) {
		holder.txtName.setText(data.getMusicName());
		long musicSize = data.getSize();
		if(data.isHQ() && data.getHQId() > 0 ){
			musicSize = data.getHQSize();
		}
		holder.txtSinger.setText(MusicBoxUtils.formatSize2String(musicSize) + "  "
				+ data.getSingerName() + " · " + data.getSpecialName());
		holder.txtMV.setVisibility(data.isHasMv() ? View.VISIBLE : View.GONE);
		// holder.txtHQ.setVisibility(data.isHQ() ? View.VISIBLE : View.GONE);
		if(StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)){//by jiangwb
			holder.txtHQ.setBackgroundColor(data.isHQ() ?  
					mContext.getResources().getColor(R.color.mbx_font_lyric_pink)
					: 
						mContext.getResources().getColor(R.color.mbx_font_lyric_gray));			
		}else{
			holder.txtHQ.setVisibility(data.isHQ() ? View.VISIBLE : View.GONE);
		}
		holder.cbExpandedMenu.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (arg1) {
					state.clear();
					state.put(position, arg1);
					holder.pnlExpandedMenu.setVisibility(View.VISIBLE);
					notifyDataSetChanged();
					BusProvider.getInstance().post(new MenuPositionEvent(position));
				} else {
					holder.pnlExpandedMenu.setVisibility(View.GONE);
					state.remove(position);
					notifyDataSetChanged();
				}
			}
		});
		holder.cbExpandedMenu.setChecked(state.get(position) == null ? false : true);

		holder.pnlLike.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (data.isFaved()) {
					new AlertDialog.Builder(mContext)
					.setTitle(R.string.mbx_hint)
					.setMessage(R.string.mbx_confirm_unlike_music)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setPositiveButton(R.string.mbx_confirm,
							new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							data.setFaved(false);
							ManagerFactory.getPlaylistInstance(getContext())
							.unLikeMusic(data);
							notifyDataSetChanged();
						}
					}).setNegativeButton(R.string.mbx_cancel, null).show();
				} else {
					data.setFaved(true);
					ManagerFactory.getPlaylistInstance(getContext()).likeMusic(data);

					notifyDataSetChanged();
				}
			}
		});

		holder.pnlDel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setMessage(R.string.mbx_download_del_hint);
				builder.setTitle(R.string.mbx_hint);
				builder.setIcon(android.R.drawable.ic_dialog_alert);
				builder.setPositiveButton(R.string.mbx_download_del_confirm,
						new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						LogUtils.d("MyMusicDownloadAdapter.java -- jiangwb", "开始删除歌曲：" + data.getMusicName());
						ManagerFactory.getDownloadInstance(getContext())
						.removeMusicFromDownloadList(data);
						getDatas().remove(data);//删除list对应的数据
						state.clear();
						notifyDataSetChanged();
						// 更新底部已下载信息
						mTvFooter.setText(MusicBoxUtils.getDownloadFooterText(mContext,
								getDatas()));
					}
				});

				builder.setNegativeButton(R.string.mbx_download_del_cancel,
						new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

				builder.create().show();
			}
		});

		if (data.isDownLoaded()) {
			holder.pnlSinger.setVisibility(View.VISIBLE);
			holder.pnlProgress.setVisibility(View.GONE);
		} else {
			holder.pnlSinger.setVisibility(View.GONE);
			holder.pnlProgress.setVisibility(View.VISIBLE);

			populateView(holder, data);
		}

		holder.ivLike.setImageResource(data.isFaved() ? R.drawable.mbx_btn_unlike_selector
				: R.drawable.mbx_btn_like_selector);
		holder.txtLike.setText(data.isFaved() ? R.string.mbx_expanded_cancel_fav
				: R.string.mbx_expanded_join_fav);
        StarAppUtils.setViewTypeFace(holder.txtHQ, false);
        StarAppUtils.setViewTypeFace(holder.txtLike, false);
        StarAppUtils.setViewTypeFace(holder.txtName, false);
        StarAppUtils.setViewTypeFace(holder.txtMV, false);
        StarAppUtils.setViewTypeFace(holder.txtSize, false);
        StarAppUtils.setViewTypeFace(holder.txtSinger, false);
        StarAppUtils.setViewTypeFace(holder.txtPlayMV, false);
	}

	/**
	 * 
	 * <br>
	 * Created 2014年9月15日 下午11:07:55
	 * 
	 * @param holder
	 * @param data
	 * @author wat.ztag
	 */
	void populateView(final MusicDownLoadViewHolder holder, MusicInfo data) {
		DownloadBytesAndStatusWrapper downloadBytesAndStatusWrapper = null;
		if(StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)){//by jiangwb
			if(data.isHQ() && data.getHQId() > 0){
				downloadBytesAndStatusWrapper = mAppDownloadHelper
						.getBytesAndStatus(data.getHQMusicUrl());		
			}else{
				downloadBytesAndStatusWrapper = mAppDownloadHelper
						.getBytesAndStatus(data.getMusicUrl());		
			}
		}else{
			downloadBytesAndStatusWrapper = mAppDownloadHelper
					.getBytesAndStatus(data.getMusicUrl());			
		}

		if (null == downloadBytesAndStatusWrapper) {
			// 异常文件，不处理
			return;
		}
		int downloadBytes = downloadBytesAndStatusWrapper.getDownloadBytes();
		int totalBytes = downloadBytesAndStatusWrapper.getTotalBytes();

		if (totalBytes <= 0) {
			holder.progress.setProgress(0);
			holder.txtSize.setText(R.string.mbx_download_waiting);
		} else if (downloadBytes < totalBytes) {
			holder.progress.setIndeterminate(false);
			holder.progress.setMax(totalBytes / n1024);
			holder.progress.setProgress(downloadBytes / n1024);
			holder.txtSize.setText(MusicBoxUtils.formatSize2String(downloadBytes) + "/"
					+ MusicBoxUtils.formatSize2String(totalBytes));
		} else {
			holder.pnlSinger.setVisibility(View.VISIBLE);
			holder.pnlProgress.setVisibility(View.GONE);
			// 更新底部已下载信息
			data.setDownLoaded(true);
			mTvFooter.setText(MusicBoxUtils.getDownloadFooterText(mContext, getDatas()));
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		ManagerFactory.getPlayerInstance().playByItem(mContext, getItem(i), getDatas(), i);
	}
}

/**
 * 
 * <br>
 * Created 2014年9月15日 下午11:07:59
 * 
 * @version
 * @author wat.ztag
 * 
 * @see
 */
class MusicDownLoadViewHolder implements UnMixable {
	TextView txtName;
	TextView txtMV;
	TextView txtHQ;
	CheckBox cbExpandedMenu;
	LinearLayout pnlExpandedMenu;
	LinearLayout pnlProgress;
	ProgressBar progress;
	TextView txtSize;
	LinearLayout pnlSinger;
	TextView txtSinger;
	LinearLayout pnlLike;
	LinearLayout pnlDel;
	ImageView ivLike;
	TextView txtLike;
    TextView txtPlayMV;
}
